package fr.nekloth.android.hinode;


import org.acra.ErrorReporter;

import fr.nekloth.android.hinode.R;

import android.app.Activity;

import android.graphics.Typeface;

import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TimePicker.OnTimeChangedListener;
import uk.me.jstott.sun.*;



public class alarmSetActivity extends Activity {

	//Variables
	public SunAlarm saConsidered;
    public static int consideredIndex = 99;
    
    int selectedVolumeLevel = applicationStartup.MENU_VOLUME_MEDIUM;

    public static Time[] referenceHours = {new Time(0,0,0d),new Time(0,0,0d),new Time(0,0,0d),new Time(0,0,0d)} ;

	public void crashDebugAdditionalInformation() {
		
		TimePicker tmPckr = (TimePicker) findViewById(R.id.tmpcker);
		CheckBox chkBox = (CheckBox) findViewById(R.id.chkActive);
		Spinner spRelative = (Spinner) findViewById(R.id.spRelative);
		Spinner spEvent = (Spinner) findViewById(R.id.spEvent);
				
		ErrorReporter.getInstance().addCustomData("Time Picker", ""+  tmPckr.getCurrentHour() + ":" + tmPckr.getCurrentMinute());
		ErrorReporter.getInstance().addCustomData("Active State", "" + chkBox.isChecked());
		ErrorReporter.getInstance().addCustomData("spRelative", ""+spRelative.getSelectedItem());
		ErrorReporter.getInstance().addCustomData("spEvent",""+spEvent.getSelectedItem());
	}

    
	public void updateReferenceHours() {
		try {
            referenceHours[SunAlarm.REFERENCE_MORNING_TWILIGHT] = Sun.morningCivilTwilightTime(applicationStartup.julianCalendar, applicationStartup.currentPosition, applicationStartup.currentTimeZone, applicationStartup.daylightSavingTime);
            referenceHours[SunAlarm.REFERENCE_SUNRISE] = Sun.sunriseTime(applicationStartup.julianCalendar, applicationStartup.currentPosition, applicationStartup.currentTimeZone, applicationStartup.daylightSavingTime);
            referenceHours[SunAlarm.REFERENCE_SUNSET] = Sun.sunsetTime(applicationStartup.julianCalendar, applicationStartup.currentPosition, applicationStartup.currentTimeZone, applicationStartup.daylightSavingTime);
            referenceHours[SunAlarm.REFERENCE_EVENING_TWILIGHT] = Sun.eveningCivilTwilightTime(applicationStartup.julianCalendar, applicationStartup.currentPosition, applicationStartup.currentTimeZone, applicationStartup.daylightSavingTime);
		} catch (IllegalArgumentException e) {
			referenceHours[SunAlarm.REFERENCE_MORNING_TWILIGHT] = new Time(5,26,0.0d);
			referenceHours[SunAlarm.REFERENCE_SUNRISE] = new Time(6,05,0.0d);
			referenceHours[SunAlarm.REFERENCE_SUNSET] = new Time(21,28,0.0d);
			referenceHours[SunAlarm.REFERENCE_EVENING_TWILIGHT] = new Time(22,7,0.0d);
		}
	}

    
    //SetView functions
	public void displaySetAlarmView() {

		applicationStartup.loadPreferences(this);
		
        Bundle b = this.getIntent().getExtras();         
        consideredIndex = b.getInt("alarmToConsider",99);
        
        if (consideredIndex==99) {
        	applicationStartup.toastInfo(this, "Error loading data... Sorry");
        	setResult(99);
        	finish();
        } else {
        	saConsidered = new SunAlarm();
        	if(consideredIndex == 1) saConsidered= applicationStartup.sAlarm1;
        	if(consideredIndex == 2) saConsidered= applicationStartup.sAlarm2;
        }
		
        //Log.d("Nekloth","MomentRef : " + saConsidered.getMomentReference());
        
		// ALARM SET VIEW
        setContentView(R.layout.alarm_set_activity);
        
        //Change the title FONT
        Typeface face=Typeface.createFromAsset(getAssets(), applicationStartup.GLOBAL_FONT_TO_USE);
        TextView tv=(TextView)findViewById(R.id.screentitle);
        tv.setTypeface(face);
        
        //Set the TimePicker format
        TimePicker tmPckr = (TimePicker) findViewById(R.id.tmpcker);
        tmPckr.setIs24HourView(true);
        
        CheckBox chkBox = (CheckBox) findViewById(R.id.chkActive);
        
        //Set the BEFORE/AFTER info
        Spinner spRelative = (Spinner) findViewById(R.id.spRelative);
        ArrayAdapter adapterRelative = ArrayAdapter.createFromResource( this, R.array.eventRelative, android.R.layout.simple_spinner_item); 
        adapterRelative.setDropDownViewResource(android.R.layout.select_dialog_item);
        spRelative.setAdapter(adapterRelative);
                
        //Set the EVENT list
        Spinner spEvent = (Spinner) findViewById(R.id.spEvent);
        ArrayAdapter adapterEvent = ArrayAdapter.createFromResource( this, R.array.events, android.R.layout.simple_spinner_item); 
        adapterEvent.setDropDownViewResource(android.R.layout.select_dialog_item);
        spEvent.setAdapter(adapterEvent);        
        
        //Define view status, according to the SunAlarm information
	        spEvent.setSelection(saConsidered.getMomentReference());
	        tmPckr.setCurrentHour(saConsidered.getAlarmHour());
	        tmPckr.setCurrentMinute(saConsidered.getAlarmMinute());        
	        if (saConsidered.getRelative()) {
	        	spRelative.setSelection(SunAlarm.BEFORE);
	        } else {
	        	spRelative.setSelection(SunAlarm.AFTER);
	        }
	        chkBox.setChecked(saConsidered.isActive());
	        
	    // Add listeners ==============================================================================
	    Button btnCancel = (Button) findViewById(R.id.btnCancel);
	    Button btnOk	 = (Button) findViewById(R.id.btnOk);
	    
	    btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {doActionsOnAlarmSetButtons(R.id.btnCancel);}
		});

	    btnOk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {doActionsOnAlarmSetButtons(R.id.btnOk);}
		});
	    
        tmPckr.setOnTimeChangedListener(new OnTimeChangedListener() {
			@Override
			public void onTimeChanged(TimePicker arg0, int arg1, int arg2) {updateConsideredAlarm();changeActiveText();}
		});
	    
      spRelative.setOnItemSelectedListener(new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {updateConsideredAlarm();changeActiveText();}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {}
      });
      
      spEvent.setOnItemSelectedListener(new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {updateConsideredAlarm();changeActiveText();}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {}
      });
      //== END LISTENERS ==========================================================================================    
        
	    changeActiveText();
	    
	    //v1.1.1 Not possible to activate without coordinates selection
	    chkBox.setEnabled(applicationStartup.applicationPOSITIONset);
	}
	
	public void changeActiveText() {
		CheckBox cb = (CheckBox) findViewById(R.id.chkActive);
		cb.setText((String)getText(R.string.activated_alarm) + " " + getText(R.string.at) + " " + saConsidered.getAlarmTimeString() );
	}

	
	//End of action method
	public void updateConsideredAlarm(){
		TimePicker tmPckr = (TimePicker) findViewById(R.id.tmpcker);
        if ((tmPckr.getCurrentHour()>23 && tmPckr.getCurrentHour()<0) || (tmPckr.getCurrentMinute()>59 && tmPckr.getCurrentMinute()<0)) {
        	applicationStartup.toastInfo(this, "How did you put a invalid value ? :-s");
        } else {
			saConsidered.setAlarmHour(tmPckr.getCurrentHour());
	        saConsidered.setAlarmMinutes(tmPckr.getCurrentMinute());
        }
	        
        Spinner spRelative = (Spinner) findViewById(R.id.spRelative);
        if (spRelative.getSelectedItemPosition()==0) {saConsidered.setIsBefore();} else {saConsidered.setIsAfter();}
        
        Spinner spEvent = (Spinner) findViewById(R.id.spEvent);
        saConsidered.setMomentReference(spEvent.getSelectedItemPosition());
        
        CheckBox chkActive = (CheckBox) findViewById(R.id.chkActive);
        if (chkActive.isChecked()) {saConsidered.activate();} else {saConsidered.desactivate();}
        
        updateReferenceHours();
        saConsidered.setTimeReference(referenceHours[saConsidered.getMomentReference()]);
        saConsidered.updateAlarmTime();
	}
	
	public void doActionsOnAlarmSetButtons(int clickedBtn) {
		if (clickedBtn == R.id.btnCancel) {
			saConsidered = null;
			setResult(98);
			finish();
		}
		
		if (clickedBtn == R.id.btnOk) {
			if (consideredIndex==99) {
			} else {
		        crashDebugAdditionalInformation();
				updateConsideredAlarm();
				if (consideredIndex == 1) applicationStartup.sAlarm1 = saConsidered;
				if (consideredIndex == 2) applicationStartup.sAlarm2 = saConsidered;
				applicationStartup.savePreferences(this);
			}
			setResult(0);
			finish();
		}
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        displaySetAlarmView();
        crashDebugAdditionalInformation();
    }	
}
